﻿//-------------------------------------------------------
// Copyright
// All rights reserved.
//
// File Name: LinkNode.h
// File Des: 链表封装
// File Summary:
// Cur Version: 1.0
// Author:
// Create Data:
// History:
//      <Author>  <Time>       <Version>      <Des>
//      lzlong    2024-1-31    1.0
//      lzlong    2024-7-12    2.0       chatgpt优化版本
//-------------------------------------------------------
#pragma once
#include <mutex>

/// <summary>
///        统一的链表封装
/// </summary>
template <class Tobj>
class GLinkNodeT {
public:
    GLinkNodeT() {
        std::lock_guard<std::mutex> lock(sm_mutex);
        m_pPrev = nullptr;
        m_pNext = sm_pHead;
        sm_pHead = static_cast<Tobj*>(this);
        if (m_pNext) {
            m_pNext->m_pPrev = sm_pHead;
        }
    }

    virtual ~GLinkNodeT() {
        std::lock_guard<std::mutex> lock(sm_mutex); 
        if (sm_pHead == this) {
            sm_pHead = m_pNext;
        }
        else {
            if (m_pPrev) {
                m_pPrev->m_pNext = m_pNext;
            }
            if (m_pNext) {
                m_pNext->m_pPrev = m_pPrev;
            }
        }
        m_pPrev = nullptr;
        m_pNext = nullptr;
    }

    static Tobj* GetHeadNode() {
        std::lock_guard<std::mutex> lock(sm_mutex);
        return sm_pHead;
    }

    Tobj* GetNextNode()const {
        return m_pNext;
    }

    Tobj* GetPrevNode()const {
        return m_pPrev;
    }

protected:
    static Tobj* sm_pHead;
    Tobj* m_pNext;
    Tobj* m_pPrev;

private:
    static std::mutex sm_mutex;
};

template <class TObj>
TObj* GLinkNodeT<TObj>::sm_pHead = nullptr;

template <class TObj>
std::mutex GLinkNodeT<TObj>::sm_mutex;